<template>
	<div class="page">
		<h1>vue-component-view</h1>
		<ul v-if="!loading">
			<li v-for="(item, index) in content" :key="index">
				<div
					class="item-text"
					@click="activeIndex = index"
					v-show="activeIndex === -1"
				>
					<p>{{ item.name }}组件</p>
					<p>路径：{{ item.path }}</p>
				</div>
				<component-item
					:comp="item"
					v-if="activeIndex === index"
					@back="activeIndex = -1"
					:keyName="'comp_' + index"
				></component-item>
			</li>
		</ul>
	</div>
</template>

<script>
import ComponentItem from "./ContentItem.vue";
import Vue from "vue";
export default {
	data() {
		return {
			componentList: [],
			loading: true,
			content: [],
			activeIndex: -1,
		};
	},
	components: { ComponentItem },
	methods: {},
	mounted() {
		this.loading = true;
		let content = this.$vcv.content || [];
		content.map((item) => {
			if (item.props || item.emits) {
				let path = item.path.replace("./", "");
				let comp = require(`../${path}`).default;
				// 如果存在props或emits
				if (item.props || item.emits) {
					let props = item.props || {};
					let emits = item.emits || {};
					let compName = "";
					if (item.name) {
						compName = item.name.toLowerCase() + "-comp";
					} else {
						compName = "anymous-comp";
					}
					// 生成新的component
					let newComp = Vue.component(compName, {
						functional: true,
						render: function(createElement) {
							return createElement(comp, {
								props: { ...props },
								on: {
									...emits,
								},
							});
						},
					});
					item.component = newComp;
				}
				if (comp.data) {
					item.data = {
						...comp.data(),
					};
				} else {
					item.data = {};
				}
				item.propsData = {
					...comp.props,
				};
				item.methods = {
					...comp.methods,
				};
				item.isSet = true;
			} else {
				let path = item.path.replace("./", "");
				let comp = require(`../${path}`).default;
				item.propsData = {
					...comp.props,
				};
				item.data = {};
				for (let key in comp.data) {
					if (key) {
						item.data[key] = JSON.stringify(comp.data[key]);
					}
				}
				item.isSet = false;
			}
		});
		this.content = content;
		this.loading = false;
	},
};
</script>

<style lang="css" scoped>
ul {
	list-style: none;
	padding: 0;
}
.item-text {
	padding: 10px 10px;
	border-bottom: 1px solid #ebeef5;
	font-size: 14px;
	text-align: left;
}
.item-text p {
	margin: 5px 0;
}
</style>
